package com.zlsy.thread.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhouliang
 * @date 2020/04/28
 **/
public class Usevolatile implements Runnable {
    volatile boolean done = false;
    AtomicInteger read = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        Usevolatile r = new Usevolatile();
        Thread thread1 = new Thread(r);
        Thread thread2 = new Thread(r);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println(r.done);
        System.out.println(r.read.get());
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
//            flipDone();
            setDone();
            read.incrementAndGet();
        }

    }

    private void setDone() {
        done = true;
    }

    private void flipDone() {
        //一旦done 取决于之前的状态，那么就是不可控的。
        done = !done;
    }
}
